#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include "log.hpp"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <signal.h>
#include <cassert>

static void service(int sock, const std::string &clientip, const uint16_t &clientport)
{
    char buffer[1024];
    while (true)
    {
        ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << clientip << ":" << clientport << "#" << buffer << std::endl;
        }
        else if (s == 0)
        {
            logMessage(NORMAL, "%s:%d shutdown,me too!", clientip.c_str(), clientport);
            break;
        }
        else
        {
            logMessage(ERROR, "read socket error,%d:%s", errno, strerror(errno));
            break;
        }
        write(sock, buffer, strlen(buffer));
    }
}

class TcpServer
{
private:
    const static int gbacklog = 20;

public:
    TcpServer(uint16_t port, std::string ip = "")
        : listensock(-1), _port(port), _ip(ip)
    {
    }

    void initServer()
    {
        // 1、创建socket 进程和文件
        listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (listensock < 0)
        {
            logMessage(FATAL, "%d%s", errno, strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "create socket success listensock: %d", listensock);

        struct sockaddr_in local;
        memset(&local, 0, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = _ip.empty() ? INADDR_ANY : inet_addr(_ip.c_str());

        if (bind(listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "bind error,%d:%s", errno, strerror(errno));
            exit(3);
        }
        if (listen(listensock, gbacklog) < 0)
        {
            logMessage(FATAL, "listen error,%d:%s", errno, strerror(errno));
            exit(4);
        }
        logMessage(NORMAL, "init server success");
    }

    void start()
    {
        signal(SIGCHLD, SIG_IGN); // 自动回收子进程资源
        while (true)
        {
            struct sockaddr_in src;
            socklen_t len = sizeof src;
            int servicesock = accept(listensock, (struct sockaddr *)&src, &len);
            if (servicesock < 0)
            {
                logMessage(ERROR, "accept error,%d:%s", errno, strerror(errno));
                continue;
            }
            uint16_t client_port = ntohs(src.sin_port);
            std::string client_ip = inet_ntoa(src.sin_addr);
            logMessage(NORMAL, "link success servicesock: %d | %s : %d |\n",
                       servicesock, client_ip.c_str(), client_port);
            // 单进程循环版
            // service(servicesock,client_ip,client_port);

            // 多进程
            pid_t id = fork();
            assert(id != -1);
            if (id == 0)
            {
                close(listensock);
                service(servicesock, client_ip, client_port);
                exit(0);
            }

            close(servicesock);
        }
    }

    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    std::string _ip;
    int listensock;
};